package logic

import (
	"context"
	"errors"
	"fmt"
	"practice-one/models/cache"
	"practice-one/models/mysql"
	"strings"
	"time"

	"practice-one/userrpc/internal/svc"
	"practice-one/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CommentAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCommentAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CommentAddLogic {
	return &CommentAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CommentAddLogic) CommentAdd(in *userrpc.CommentAddRequest) (*userrpc.CommentAddResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	if err := user.FindUserById(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("用户不存在")
	}
	var goods mysql.Goods
	if err := goods.FindGoodsById(mysql.DB, in.GoodsId); err != nil {
		return nil, errors.New("商品不存在")
	}

	if strings.Contains(in.Comments, "欺诈") == true || strings.Contains(in.Comments, "伪劣") == true {
		return nil, errors.New("评论内容中有敏感词")
	}
	comment := &mysql.Comment{
		UserId:   in.UserId,
		GoodsId:  in.GoodsId,
		Comments: in.Comments,
	}
	if err := comment.CommentAdd(mysql.DB); err != nil {
		return nil, err
	}
	key := fmt.Sprintf("comment_%s", in)
	cache.Rdb.Set(l.ctx, key, in.Comments, time.Minute*15)

	return &userrpc.CommentAddResponse{
		CommentId: int64(comment.ID),
	}, nil
}
